package com.control;

import com.dao.QuestionDaoImpl;
import com.dao.UserDao;
import com.dao.UserDaoImpl;
import com.model.Question;

import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import com.dao.QuestionDao;
import com.model.User;

@WebServlet("/score.do")
public class ScoreServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        QuestionDao questionDao = new QuestionDaoImpl();
        ArrayList<Question> questions = null;
        double score = 0;
        questions = (ArrayList<Question>) req.getSession().getAttribute("questions");
        int n = (int) req.getSession().getAttribute("n");

        int realN = 0;
        realN = questionDao.getQuestionRealNum();
        //题库数目小于要求数目时,以题库数目为准
        realN = realN < n ? realN : n;
        int rightN = 0;
        for (Question question : questions) {
            String[] userOptionId = req.getParameterValues("" + question.getqId());
            if (userOptionId == null) {
                continue;
            }
            if (questionDao.isRightAns(userOptionId, question.getqId())) {
                rightN++;
            }
        }
        UserDao userDao = new UserDaoImpl();
        score = 1.0 * rightN / realN * 100;
        User loginUser = (User) req.getSession().getAttribute("loginUser");
        loginUser.setScore(score);
        userDao.updateUserInfo(loginUser);
        loginUser.setScore(score);
        resp.sendRedirect("displayScore.jsp");
    }
}
